package com.tianyi.company;


import com.tianyi.dao.entity.company.Company;
import com.tianyi.dao.entity.company.CompanyExample;
import com.tianyi.dao.entity.sysUser.SysUser;
import com.tianyi.dao.mapper.CompanyMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 公司service
 *
 * @author cuixuhui
 * @date 2020/05/07
 */
@Service
public class CompanyService {

    private static final Logger logger = LoggerFactory.getLogger(CompanyService.class);

    @Autowired
    private CompanyMapper companyMapper;

    public Company queryComUserCompanyByParentId(Long comUserId){

        CompanyExample example = new CompanyExample();
        example.createCriteria().andComUserIdEqualTo(comUserId);
        List<Company> companies = companyMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(companies)){
            return null;
        }
        return companies.get(0);
    }

    public void insertUserCompany(Company comUserCompany) {
        if (Objects.isNull(comUserCompany)){
            return;
        }
        companyMapper.insert(comUserCompany);
    }

    public void updateUserCompanyByPrimaryKeySelective(Company comUserCompany) {
        if (Objects.isNull(comUserCompany)){
            return;
        }
        companyMapper.updateByPrimaryKeySelective(comUserCompany);
    }

    public Map<Long, String> queryCompanyNameMapByComUserIds(List<Long> comUserIds) {

        CompanyExample example = new CompanyExample();
        example.createCriteria().andComUserIdIn(comUserIds);
        List<Company> companies = queryByComUserIds(comUserIds);
        return ListUtils.emptyIfNull(companies).stream().collect(Collectors.toMap(Company::getId, Company::getComName, (oldOne, newOne) -> newOne));
    }

    public List<Company> queryByComUserIds(List<Long> comUserIds) {

        CompanyExample example = new CompanyExample();
        example.createCriteria().andComUserIdIn(comUserIds);
        List<Company> companies = companyMapper.selectByExample(example);
        return companies;
    }

    /**
     * 删除公司信息
     * @param id
     */
    public void deleteCompanyById(Long id) {
        if (Objects.isNull(id)){
            return;
        }
        companyMapper.deleteByPrimaryKey(id);
    }
}
